import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from '@/route/routes.js'
import store from '@/store'




Vue.use(VueRouter);

// 重写push
const oldPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve = () => { }, reject = () => { }) {
    oldPush.call(this, location, resolve, reject)
}

const router = new VueRouter({
    // 路由模式
    mode: 'history',
    routes: routes,
    scrollBehavior() {
        return { x: 0, y: 0 }
    }
})

const whitePath = ['login', 'register', 'home', 'search', 'detail', 'addcartsuccess']

router.beforeEach(async (to, from, next) => {
    // console.log(1);

    let token = store.state.user.token

    // 当有token时候
    if (token) {
        // 如果要去首页，则回到首页
        if (to.name === 'login') {
            next('/home')

        } else {
            // 获取userInfo
            const isUserInfo = store.state.user.userInfo.id
            // 如果去的别的页面判断是否有用户信息,有则直接放行
            if (isUserInfo) {
                next();
            } else {
                // 如果去的别的页面判断是否有用户信息,没有则先获取再跳转
                try {
                    // console.log(store);
                    await store.dispatch('user/getUserInfo');
                    next();
                } catch (e) {
                    // console.log(store);
                    alert(e.message + '，或者登录已经过期')
                    store.commit('user/resetUserInfo')
                    next('/login')
                }
            }
        }

    } else {
        // 判断token不存在的时候
        if (whitePath.includes(to.name)) {
            // console.log(3);
            next();
        } else {
            next('/login')
            // console.log(4);
        }
    }


})


export default router